--[[
fetch upstream server and save
--]]

package.path = './lua/zk/?.lua;' .. package.path
ngx.log(ngx.ERR, 'upstream_fetcher.lua start')


local myutils = require('myutils')
local request = require('request')
local response = require('response')
local tcp = ngx.socket.tcp
ngx.log(ngx.ERR, 'upstream_fetcher new tcp')
local sock = assert(tcp(),'tcp() error')

local _host = '127.0.0.1'
local _port = 2181

local function _log(str)
  ngx.log(ngx.ERR, str)
end

local _status = {
  xid = 0,
  lastZxidSeen = 0, -- Uint8Array[8]
  timeOut = 30000,
  sessionId = 0, -- Uint8Array[8]
  passwd = myutils.makeBuffer(16) -- Uint8Array[16]
}

local reqConnect = request:new("ConnectRequest", nil, {
  protocolVersion = 0,
  lastZxidSeen = _status.lastZxidSeen,
  timeOut = _status.timeOut,
  sessionId = _status.sessionId,
  passwd = _status.passwd
})
--myutils.printTbl(req1.payload)
--myutils.writeFile(req1:toStream())


assert(sock:connect(_host, _port))
local conn = sock

function sendByteAndWaitResponse(req, responseType)
  conn:send(req:toStream())
  local bytes = conn:receive(4)
  -- myutils.writeFile(bytes)
  local length = response.unpackInt(bytes)
  _log(responseType .. ', length=' .. length)
  local bytes = conn:receive(length)
  -- myutils.writeFile(bytes)
  local resp = response:new(responseType, bytes)
  resp:parse()
  return resp
end


local respConnect = sendByteAndWaitResponse(reqConnect, "ConnectResponse")
_status.timeout = respConnect.payload.timeout
_status.sessionId = respConnect.payload.sessionId
_status.passwd = respConnect.payload.passwd

--[[
TODO need better encapsulate at step ConnectRequst/response
--]]





-- conn:close()